package com.enjoyor.health.HGPT.web.rest;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enjoyor.health.HGPT.core.config.ParamConfig;
import com.enjoyor.health.HGPT.core.dto.ReservationWeekDto;
import com.enjoyor.health.HGPT.core.dto.ReservationWeekDtoV2;
import com.enjoyor.health.HGPT.core.entity.FileInfo;
import com.enjoyor.health.HGPT.core.entity.News;
import com.enjoyor.health.HGPT.core.entity.PhysicalExaminationPackage;
import com.enjoyor.health.HGPT.core.service.IPhysicalExaminationPackageService;
import com.enjoyor.health.HGPT.service.BizFileService;
import com.enjoyor.health.HGPT.service.BizNewsService;
import com.enjoyor.health.HGPT.service.BizReservationService;
import com.enjoyor.health.HGPT.web.CodeEnum;
import com.enjoyor.health.HGPT.web.RetResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * web页的新闻管理接口
 * @author Zhu Min
 * @date 2023/11/1 11:43
 */
@Api(value = "新闻页面", tags = {"Web页面管理接口"})
@CrossOrigin
@RequestMapping("/rest")
@RestController
public class WebNewsController {

    @Autowired
    private ParamConfig paramConfig;
    @Autowired
    private BizFileService bizFileService;
    @Autowired
    private BizNewsService bizNewsService;


    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题"),
            @ApiImplicitParam(name = "type", value = "类型：图文、视频"),
            @ApiImplicitParam(name = "status", value = "文章状态：1 正常 0 下架"),
            @ApiImplicitParam(name = "page", value = "页码，不为空"),
            @ApiImplicitParam(name = "size", value = "每页条数，不为空")})
    @RequestMapping(value = "/news/getPage", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult getNewsPage(
            String title,
            String type,
            String status,
            @RequestParam(required = true, defaultValue = "1") int page,
            @RequestParam(required = true, defaultValue = "10")int size){
        Page<News> newsPage = bizNewsService.getNewsPage(type, status, title, page, size);
        return new RetResult().setResult(newsPage);
    }

    @RequestMapping(value = "/news/getById", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult getNewsById(String id){
        return new RetResult().setResult(bizNewsService.getRawNewsById(id));
    }

    @PostMapping("/news/addOrUpdate")
    public RetResult addOrUpdateNews(News news){
        News n = bizNewsService.addOrUpdateNews(news);
        return new RetResult().setResult(n);
    }

    @RequestMapping(value = "/news/setUp", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult setUp(String id){
        News n = bizNewsService.updateUp(id);
        return new RetResult().setResult(n);
    }

    @RequestMapping(value = "/news/setStatus", method = { RequestMethod.GET, RequestMethod.POST })
    public RetResult setStatus(String id){
        News n = bizNewsService.updateStatus(id);
        return new RetResult().setResult(n);
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/file/upload")
    public RetResult upload(MultipartFile file, Integer type){
//      1.拼接转存的位置
//      获取文件的原始名
        String originalFilename = file.getOriginalFilename();   //abc.jpg
//      文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//       也可以使用UUID生成文件名，防止文件名称重复导致覆盖原文件
        String filename = UUID.randomUUID().toString();   //缺少后缀
        String url= paramConfig.getUploadPath() + filename + suffix;
//      2. 判断转存的目录是否存在
//         File既可以代表一个目录，又可以代表一个文件
        File dir = new File(paramConfig.getUploadPath());
//         判断当前目录是否存在
        if (!dir.exists()){
//          不存在的时候进行创建
            dir.mkdirs();
        }

        FileInfo info = bizFileService.saveFileInfo(filename + suffix, originalFilename, type, 1);

//      转存临时文件到指定的位置  参数是一个URL路径
        try {
            file.transferTo(new File(url));
            return new RetResult().setResult(info);
        }catch (IOException e){
            return new RetResult(CodeEnum.ERROR).setResult(e.getMessage());
        }
    }

    @ApiOperation(value = "文件下载")
    @RequestMapping(value = "/file/download", method = { RequestMethod.GET, RequestMethod.POST })
    public ResponseEntity<InputStreamResource> downloadFile(String fileId)
            throws IOException {

        FileInfo fileInfo = bizFileService.findById(fileId);
        if (fileInfo == null){
            return ResponseEntity.notFound().build();
        }

        //读取文件
        String filePath = paramConfig.getUploadPath() + fileInfo.getFileName();
        FileSystemResource file = new FileSystemResource(new File(filePath).getCanonicalPath());
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileInfo.getFileOriginalName()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }




}
